#!/bin/bash

# 设置API的URL
API_URL="http://localhost:3300"

# 解析命令行参数
method=$1
endpoint=$2
data=$3

# 发送GET请求
function send_get_request() {
	curl -X GET "${API_URL}/${endpoint}"
}

# 发送POST请求
function send_post_request() {
	curl -X POST -H "Content-Type: application/json" -d "${data}" "${API_URL}/${endpoint}"
}

# 发送PUT请求
function send_put_request() {
	curl -X PATCH -H "Content-Type: application/json" -d "${data}" "${API_URL}/${endpoint}"
}

# 发送DELETE请求
function send_delete_request() {
	curl -X DELETE "${API_URL}/${endpoint}"
}

# 执行请求
function execute_request() {
	case $method in
	"get")
		send_get_request
		;;
	"post")
		send_post_request
		;;
	"patch")
		send_put_request
		;;
	"delete")
		send_delete_request
		;;
	*)
		echo "Invalid method: $method"
		;;
	esac
}

# 检查必要参数
if [[ -z $method || -z $endpoint ]]; then
	echo "Usage: ./test_api.sh [method] [endpoint] [data (optional)]"
	exit 1
fi

clear
splitstr="="                              # 分隔符
endstr="-"                                # 分隔符
ScreenLen=$(stty size | awk '{print $2}') # 获取屏幕宽度

# 调用执行请求
echo "[$method] ${API_URL}/$endpoint"
# 打印分割线
yes ${splitstr} | sed ''''${ScreenLen}'''q' | tr -d "\n" && echo
execute_request

# 检查返回状态码
status_code=$(curl -s -o /dev/null -w "%{http_code}" "${API_URL}/${endpoint}")
if [[ $status_code -ne 200 ]]; then
	echo "Request failed with status code: $status_code"
	exit 1
fi

echo -e '\n'
yes ${endstr} | sed ''''${ScreenLen}'''q' | tr -d "\n" && echo

# 示例命令
# ./request GET users
# ./request POST users '{"name": "John", "email": "john@example.com"}'
# ./request PUT users/1 '{"name": "John Doe", "email": "johndoe@example.com"}'
# ./request DELETE users/1
